package com.hejjon.knowledgebase.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.hejjon.knowledgebase.exception.BusinessException;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

/**
 * @author:
 * @date: 2022-12-06 10:38:43
 * @since: 1.0
 */
public class JwtUtil {


    /**
     * 生成token
     * @param userId
     * @param pwd
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String getLoginToken(Long userId, String pwd) {

        Date start = new Date();
        long timestamp = System.currentTimeMillis();
        long endstamp = timestamp + 60 * 60 * 1000;
        Date end = new Date(endstamp);
        JWTCreator.Builder builder = JWT.create().withAudience(userId + "").withIssuedAt(start).withExpiresAt(end);
        String token = "";

        try {
            token = builder.sign(Algorithm.HMAC256(pwd));
        } catch (UnsupportedEncodingException e) {
            throw new BusinessException("生成认证Token失败, 异常信息: " + e.getMessage());
        }
        return token;
    }


    /**
     *  解析token, 获取用户ID
     * @param token
     * @return
     */
    public static Long parseToken(String token) {
        DecodedJWT decode = JWT.decode(token);
        List<String> audience = decode.getAudience();
        if (audience != null && !audience.isEmpty()) {
            String userIdStr = audience.get(0);
            return Long.valueOf(userIdStr);
        }
        return null;
    }





}
